package com.cskaoyan.shopping.api;

import com.cskaoyan.mall.commons.result.ServiceCallResponse;
import com.cskaoyan.mall.commons.result.ServiceCallResponseUtil;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemServiceResponse;
import com.cskaoyan.mall.dto.ProductDetailDto;
import com.cskaoyan.mall.dto.ProductDetailServiceResponse;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * @auther cskaoyan
 * @date 2022/8/24:14:56
 */
@RestController
@Slf4j
public class OrderApiImpl {

    @Autowired
    IProductService productService;


    @GetMapping(value = "/rpc/product/detail")
    ServiceCallResponse<ProductDetailDto> getProductDetail(@RequestParam("id") Long id) {
        ProductDetailDto productDetail = productService.getProductDetail(id);
        ServiceCallResponseUtil<ProductDetailDto> responseUtil = new ServiceCallResponseUtil<>();
        return responseUtil.ok(productDetail);
    }

    @DeleteMapping(value = "clear/carts")
    ClearCartItemServiceResponse clearCartItemByUserID(@RequestBody ClearCartItemRequest request){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");

        RedissonClient redissonClient = Redisson.create(config);
        RMap<String, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        @NotEmpty List<Long> productIds = request.getProductIds();
        if (productIds != null){
            for (Long productId : productIds) {
                map.remove(productId.toString());
            }
        }
        log.debug("clear carts");
        return null;
    }
}
